package io.kiki.stack.http.feign.form.spring;

import feign.codec.EncodeException;
import feign.form.multipart.AbstractWriter;
import feign.form.multipart.Output;
import lombok.val;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * A Spring single file writer.
 *
 * @author Artem Labazin
 */
public class SpringSingleMultipartFileWriter extends AbstractWriter {

    @Override
    public boolean isApplicable(Object value) {
        return value instanceof MultipartFile;
    }

    @Override
    protected void write(Output output, String key, Object value) throws EncodeException {
        val file = (MultipartFile) value;
        writeFileMetadata(output, key, file.getOriginalFilename(), file.getContentType());

        byte[] bytes;
        try {
            bytes = file.getBytes();
        } catch (IOException ex) {
            throw new EncodeException("Getting multipart file's content bytes error", ex);
        }
        output.write(bytes);
    }
}
